const baseStorage = (storage: Storage, key?: any, value?: null) => {
  if (!key) {
    return {
      remove: (key: any) => {
        return storage.removeItem(key);
      },
      clear: () => {
        return storage.clear();
      },
    };
  }
  if (value == null) {
    const rst = storage.getItem(key);
    try {
      return JSON.parse(rst as string);
    } catch (e) {
      return rst || undefined;
    }
  }
  const val = typeof value === "string" ? value : JSON.stringify(value);
  return storage.setItem(key, val.replace(/^"(.*)"$/, "$1"));
};

// localStorage 存储和取值方法
export const storage = (key?: string, value?: any) => {
  return baseStorage(window.localStorage, key, value);
};

// sessionStorage 存储和取值方法
export const sessionStorage = (key?: string, value?: any) => {
  return baseStorage(window.sessionStorage, key, value);
};
